package com.frank.wechat.controller;

import com.frank.wechat.handler.WeChatMessageFactory;
import com.frank.wechat.utils.MessageUtil;
import com.frank.wechat.utils.Sha1;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/14
 * @description 用于接收微信回调的控制器
 */
@Slf4j
@RestController
public class CallBackController {

    private static final String TOKEN = "FrankZouChinaChangeSha";

    private final WeChatMessageFactory weChatMessageFactory;

    public CallBackController(WeChatMessageFactory weChatMessageFactory) {
        this.weChatMessageFactory = weChatMessageFactory;
    }

    @GetMapping("/test")
    public String test() {
        return "Test";
    }

    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("WeChat 验签请求参数: signature: {}, timestamp: {}, nonce: {}, echostr: {}", signature, timestamp, nonce, echostr);
        String shaStr = Sha1.getSha1(TOKEN, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        } else {
            return "非法请求";
        }
    }

    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam String signature,
                           @RequestParam String timestamp,
                           @RequestParam String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到 WeChat 请求， 请求参数: requestBody: {}, signature: {}, timestamp: {}, nonce: {}, msg_signature: {}", requestBody, signature, timestamp, nonce, msgSignature);
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String messageType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        StringBuilder messageBuilder = new StringBuilder(messageType);
        if (StringUtils.isNotBlank(event)) {
            messageBuilder.append(".").append(event);
        }
        String messageKey = messageBuilder.toString();
        if (weChatMessageFactory.getHandler(messageKey) != null) {
            String response = weChatMessageFactory.getHandler(messageKey).handle(messageMap);
            log.info("WeChat 回复消息: {}", response);
            return response;
        }
        return "非法请求";
    }
}
